package org.cmg.study.spring.controller;

import org.cmg.study.spring.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author CMG
 * @version 1.0
 * @cLassName UserController
 * @description
 * @date 2021/9/6 10:35
 **/
@Controller
public class UserController {
    /**
     * 登陆页面初始化
     * @return
     */
    @RequestMapping("/toLogin")
    public String initLogin(){
        return "login";
    }

    /**
     * 处理登陆功能
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session){
        System.out.println(user);
        if("xg".equals(user.getName()) && "123456".equals(user.getPassword())){
            //登录成功，将用户信息保存到session中
            session.setAttribute("user", user);
            //重定向到主页面的跳转方法
            return "redirect:main";
        }
        model.addAttribute("msg", "用户名或密码错误，请重新登录！");
        return "login";
    }

    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping("/main")
    public String toMain(){
        return "main";
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //清楚session
        session.invalidate();
        return "login";
    }
}
